let app = getApp();

Page({
  data: {
    url:'',
    user: null,
    goods: [
      {
        id: 1,
        name: "心理测评券",
        desc: "免费参与一次专业心理测评",
        point: 100,
        image: "/images/article14.jpg"
      },
      {
        id: 2,
        name: "咨询优惠券",
        desc: "心理咨询享8折优惠",
        point: 200,
        image: "/images/article12.jpg"
      },
      {
        id: 3,
        name: "冥想音频包",
        desc: "包含10节正念冥想音频",
        point: 50,
        image: "/images/article13.jpg"
      },
      {
        id: 4,
        name: "精美电子证书",
        desc: "完成课程可获得专属电子证书",
        point: 300,
        image: "/images/article11.jpg"
      }
    ]
  },

  // 兑换按钮点击
  onExchange(e) {
    const id = e.currentTarget.dataset.id;
  const good = this.data.goods.find(g => g.id === id);
  const user = this.data.user || { point: 0 };

  // 如果用户没登录
  if (!user) {
    wx.showToast({ title: '请先登录', icon: 'none' });
    return;
  }

  // 如果积分不足，直接提示，不再弹窗确认
  if (good.point > user.point) {
    wx.showToast({ 
      title: '积分不足', 
      icon: 'none' 
    });
    return;
  }

  // 积分足够，弹出确认兑换
  wx.showModal({
    title: '确认兑换',
    content: `确定使用 ${good.point} 积分兑换【${good.name}】吗？`,
    success: (res) => {
      if (res.confirm) {
        const newUser = { ...user, point: user.point - good.point };
        wx.setStorageSync('user', newUser);
        this.setData({ user: newUser });

        // 更新商品状态：重新计算所有商品是否可兑换
        const updatedGoods = this.data.goods.map(item => ({
          ...item,
          isDisabled: item.point > newUser.point
        }));
        this.setData({ goods: updatedGoods });

        wx.showToast({
          title: '兑换成功',
          icon: 'success'
        });
      }
    }
  });
  },
  onLoad(options) {
    this.setData({
      url:app.globalData.url
    })
    // 获取用户信息
    const user = wx.getStorageSync('user');
    this.setData({ user });
  },
  showNotEnoughPoints() {
    wx.showToast({ title: '积分不足', icon: 'none' });
  },
  onShow() {
    const user = wx.getStorageSync('user') || { point: 0 };
  
  const goods = this.data.goods.map(good => ({
    ...good,
    isDisabled: good.point > user.point
  }));

  this.setData({ user, goods });
  }
});